import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter_juwo/provider/TaskTimerBottomModel.dart';
import 'package:flutter_juwo/provider/TaskTimerModel.dart';
import 'package:flutter_juwo/ui/custom/TimerWidget.dart';
import 'package:flutter_juwo/ui/custom/real_rich_text.dart';
import 'package:flutter_juwo/ui/custom/save_pic_widget.dart';
import 'package:flutter_juwo/ui/custom/select_pic_widget.dart';
import 'package:flutter_juwo/ui/model/base_entity.dart';
import 'package:flutter_juwo/ui/pages/photoHero/PhotoHeroUtil.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:provider/provider.dart';

import 'model/dotask_entity.dart';
import 'model/task_step_entity.dart';
import 'dart:convert' as convert;

class TaskStepPage extends StatefulWidget {
  final String id;

  TaskStepPage(this.id);

  @override
  _TaskStepPageState createState() => _TaskStepPageState();
}

class _TaskStepPageState extends State<TaskStepPage> {
  // with WidgetsBindingObserver
  MyPageState ps = MyPageState.LOADING;
  TaskStepEntity _entity;
  var jsonMap;
  SwiperController _swiperController;
  int currentStep = 0;
  int swipIndex = 0;
  int currentState = 0;
  int bottomTime = 0;
  int topTime = 0;
  int index = 0; //换一组
  String keyName; //换一组

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //  WidgetsBinding.instance.addObserver(this);
    _swiperController = SwiperController();
    this.getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: UiUtils.appBar(context, "进行任务"),
      body: getContent(),
    );
  }

  getContent() {
    if (ps == MyPageState.LOADING) {
      return LoadingPage();
    }
    if (ps == MyPageState.HAVE_DATA) {
      return getBody();
    }

    return LoadingPage();
  }

  var jsonData;

  void getData() {
    FormData formData = FormData.from({"id": widget.id});
    DioManager.getInstance().post(Api.TASK_DETAIL, formData, (jsonStr) {
      jsonMap = jsonStr;
      // print(
      //     "json-map:${jsonStr["data"]["stepArr"][1]["detailArr"]["browse"][0]["image"]}");

      jsonData = convert.jsonEncode(jsonStr);

      print("--json-${convert.jsonEncode(jsonStr)}");
      _entity = TaskStepEntity.fromJson(jsonStr);
      if (null == _entity) {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        NavigatorUtils.goBack(context);
        return;
      }

      if (_entity.code != 200) {
        ToastUtil.showShortErrToast(_entity.message);
        NavigatorUtils.goBack(context);
        return;
      }
      print("------------currentStep");
      currentStep = int.parse(_entity.data.step);
      print("------------$currentStep");
      swipIndex = currentStep;
      ps = MyPageState.HAVE_DATA;

      bottomTime = _entity.data.endtime - _entity.data.current;

      topTime = _entity.data.downTimes - _entity.data.current;

      setState(() {});
    }, (err) {
      ToastUtil.showShortErrToast(Api.ERR_TIME_OUT);
      NavigatorUtils.goBack(context);
    });
  }

  getBody() {
    return Column(
      children: <Widget>[
        getRowTimer(),
        Expanded(
          flex: 1,
          child: Container(
              child: Swiper.children(
            autoplay: false,
            loop: false,
            controller: _swiperController,
            index: swipIndex,
            onIndexChanged: (index) {
              swipIndex = index;
            },
            pagination: new SwiperPagination(
              margin: new EdgeInsets.fromLTRB(
                  0.0, 0.0, 0.0, ScreenUtil().setWidth(30)),
              builder: new DotSwiperPaginationBuilder(
                  color: Colours.appC4,
                  activeColor: Colours.appC16,
                  size: ScreenUtil().setWidth(20),
                  activeSize: ScreenUtil().setWidth(30)),
            ),
            children: getList(),
          )),
        )
      ],
    );
  }

  getList() {
    List<Widget> list = [];

    for (int i = 0; i < _entity.data.stepArr.length; i++) {
      list.add(getItem(_entity.data.stepArr[i], i));
    }

    return list;
  }

  Widget getItem(TaskStepDataSteparr step, int i) {
    List<Widget> list = [];
    list.add(getRow1(step, i, _entity.data.stepArr.length));

    /// 步骤名称为  “查找商品” ||“查找产品” 时候
    /// 提示 使用xx账号操作 基本信息？
    if (step.name == "查找产品" || step.name == "查找商品") {
      list.add(getRow2());
      list.add(getLine());
      list.add(getInfor());
    }

    list.add(getRow3(step.memo));

    ///展示 browse 信息
    if (step.detailArr.browse.length > 0) {
      if (step.name == "查找产品" || step.name == "查找商品") {
        list.add(getTaskName("关键词:", _entity.data.keywords));
        list.add(getTaskName("产品属性:", _entity.data.sx));
        list.add(getTaskName("任务名称:", _entity.data.name));
      }

      ///展示的信息
      for (int j = 0; j < step.detailArr.browse.length; j++) {
        if (step.detailArr.browse[j].cateFlg == 1) {
          list.add(getBrowseItem("${step.detailArr.browse[j].name}",
              step.detailArr.browse[j].value));
        } else if (step.detailArr.browse[j].cateFlg == 2) {
          list.add(getBrowseItem2(step.detailArr.browse[j]));
        } else {
          if (step.name == "加购--和主产品一起拍下") {
            list.add(getBrowseItem3(step.detailArr.browse[j], i, j));
          }
        }
      }
    }

    list.add(getLine());

    ///展示要 edit 的信息
    for (int j = 0; j < step.detailArr.edit.length; j++) {
      /// 1.输入文本
      if (step.detailArr.edit[j].cateFlg == 1) {
        list.add(getCateFlgTitle(step.detailArr.edit[j]));
        TextEditingController controller =
            TextEditingController(text: step.detailArr.edit[j].value);
        controller.addListener(() {
          _entity.data.stepArr[i].detailArr.edit[j].value = controller.text;
        });
        list.add(getCateFlg1(step.detailArr.edit[j], controller,
            hint: step.detailArr.edit[j].example));
        //  _controllerList.addAll({});
        continue;
      }

      /// 2.输入答案（需要校验）
      if (step.detailArr.edit[j].cateFlg == 3) {
        list.add(getCateFlg3Title(step.detailArr.edit[j]));

        TextEditingController controller =
            TextEditingController(text: step.detailArr.edit[j].value);
        controller.addListener(() {
          _entity.data.stepArr[i].detailArr.edit[j].value = controller.text;
        });

        list.add(getCateFlg3(step.detailArr.edit[j], controller));
        continue;
      }

      /// 4.显示图片组
      if (step.detailArr.edit[j].cateFlg == 4) {
        list.add(getText("请点击下载下方图片，并且在评价的时候使用这些图片"));
        Map json = convert.jsonDecode(jsonData);
        list.add(getCateFlg4(
            json['data']['stepArr'][i]['detailArr']['edit'][0]['example']));
        // list.add(getCateFlg4(step.detailArr.edit[j].example));
        if (null != step.detailArr.edit[j].group &&
            step.detailArr.edit[j].group.isNotEmpty) {
          list.add(getText("评论要点:\t\t${step.detailArr.edit[j].group}"));
        }

        continue;
      }

      /// 5.上传图片组
      if (step.detailArr.edit[j].cateFlg == 5) {
        list.add(getCateFlgTitle(step.detailArr.edit[j]));
        //已经上传过图片显示
        if (i < currentStep && step.detailArr.edit[j].value != "") {
          list.add(getCateFlg5(step.detailArr.edit[j].value));
          continue;
        }
        //未上传图片时显示
        list.add(getPics(i, j));
        continue;
      }

      /// 6.输入 粘贴并核对
      if (step.detailArr.edit[j].cateFlg == 6) {
        list.add(getCateFlgTitle(step.detailArr.edit[j], isShowRight: false));
        TextEditingController controller =
            TextEditingController(text: step.detailArr.edit[j].value);
        controller.addListener(() {
          _entity.data.stepArr[i].detailArr.edit[j].value = controller.text;
        });

        list.add(getCateFlg6(step.detailArr.edit[j], controller));
        list.add(getButton(controller.text, i, j));
        continue;
      }
    }

    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(10),
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(90)),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6), color: Colours.white),
      child: Column(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: ListView(
              children: list,
            ),
          ),
          getBottom(i)
        ],
      ),
    );
  }

  ///显示步骤说明
  Widget getRow3(String memo) {
    return Container(
      padding: EdgeInsets.all(ScreenUtil().setWidth(20)),
      margin: EdgeInsets.all(ScreenUtil().setWidth(20)),
      decoration: BoxDecoration(
          color: Color(0xFFfef0f0), borderRadius: BorderRadius.circular(6)),
      child: Text(
        memo,
        style: TextStyles.custom(
            28, Color(0xFFf56c6c), Font.PingFangMedium),
      ),
    );
  }

  ///请使用 xxx操作
  Widget getRow2() {
    return Container(
      margin: EdgeInsets.only(left: ScreenUtil().setWidth(20)),
      child: Row(
        children: <Widget>[
          Container(
            child: Text(
              "请使用${_entity.data.platname}:",
              style: TextStyles.custom(
                  30, Colours.appC2, Font.PingFangMedium),
            ),
          ),
          Container(
            child: Text(
              "${_entity.data.account}",
              style: getRightTextStyle(),
            ),
          ),
          Container(
            child: Text(
              "进行操作",
              style: TextStyles.custom(
                  30, Colours.appC2, Font.PingFangMedium),
            ),
          ),
        ],
      ),
    );
  }

  ///倒计时
  Widget getRow1(TaskStepDataSteparr step, int i, int length) {
    return Container(
      margin: EdgeInsets.all(ScreenUtil().setWidth(20)),
      child: Row(
        children: <Widget>[
          Container(
            child: Text(
              step.name,
              style: TextStyles.custom(
                  28, Colours.appC16, Font.PingFangMedium),
            ),
          ),
          Expanded(
            flex: 1,
            child: Container(
              alignment: Alignment.centerRight,
              child: Text(
                "${i + 1}/$length",
                style: TextStyles.custom(
                    28, Colours.appC16, Font.PingFangMedium),
              ),
            ),
          ),
        ],
      ),
    );
  }

  //线
  Widget getLine() {
    return Container(
      margin: EdgeInsets.all(ScreenUtil().setWidth(20)),
      child: UiUtils.divider(height: 2),
    );
  }

  //获取此单信息
  Widget getInfor() {
    return Container(
      margin: EdgeInsets.all(ScreenUtil().setWidth(20)),
      child: Row(
        children: <Widget>[
          Container(
              child: PhotoHeroUtil.photoHeroNet(context, _entity.data.exampic,
                  width: 120)),
          Expanded(
            flex: 1,
            child: Container(
              height: ScreenUtil().setWidth(120),
              margin: EdgeInsets.only(left: ScreenUtil().setWidth(30)),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text("店铺名称:",
                          style: TextStyles.custom(30, Colours.appC2,
                              Font.PingFangRegular)),
                      Text(
                        "${_entity.data.merchantStore}",
                        style: TextStyles.custom(
                            28, Colours.appC1, Font.PingFangMedium),
                      )
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text("成交价格:",
                          style: TextStyles.custom(28, Colours.appC2,
                              Font.PingFangRegular)),
                      Text("${_entity.data.priceGoods}元",
                          style: getLeftTextStyle())
                    ],
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget getBrowseItem3(
      TaskStepDataSteparrDetailarrBrowse browse, int i, int j) {
    var item = jsonMap["data"]["stepArr"][i]["detailArr"]["browse"][j];
    var imageUrl = item["image"];
    var num = item["num"];
    var price = item["price"];
    var shuxing = item["shuxing"];
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            child: Text(
              "产品${j + 1}",
              style: TextStyles.custom(
                  30, Colours.appC10, Font.PingFangMedium),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: ScreenUtil().setWidth(20)),
            child: Row(
              children: <Widget>[
                Container(
                  child: Container(
                    child: PhotoHeroUtil.photoHeroNet(context, imageUrl,
                        width: 120),
                  ),
                ),
                Expanded(
                  child: Container(
                    margin: EdgeInsets.only(left: ScreenUtil().setWidth(40)),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: <Widget>[
                        Container(
                          child: Text(
                            "店内浏览找到商品，并加入购物车与主产品一同付款",
                            style: TextStyles.custom(28, Colours.appC51,
                                Font.PingFangMedium),
                          ),
                        ),
                        Container(
                          margin:
                              EdgeInsets.only(top: ScreenUtil().setWidth(10)),
                          child: RealRichText([
                            TextSpan(
                                text: "拍:",
                                style: TextStyles.custom(26, Colours.appC51,
                                    Font.PingFangMedium)),
                            TextSpan(
                                text: "$shuxing $num件 $price元",
                                style: TextStyles.custom(26, Colours.appC16,
                                    Font.PingFangMedium))
                          ]),
                        )
                      ],
                    ),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget getBrowseItem(String s, String name) {
    keyName = name;
    List<String> list;
    int lenth = 0;
    if (s == "关键词") {
      lenth = getLenth(name);
      list = name.split("，");
      keyName = list[index];
    }

    return Container(
      margin: EdgeInsets.all(ScreenUtil().setWidth(20)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Container(
              child: Text(
                "$s:",
                style: getLeftTextStyle(),
              ),
            ),
          ),
          Expanded(
            flex: 2,
            child: Container(
              alignment: Alignment.centerRight,
              child: Text(
                keyName,
                maxLines: 10,
                overflow: TextOverflow.ellipsis,
                style: getRightTextStyle(),
              ),
            ),
          ),
          s == "关键词" && lenth > 1
              ? Container(
                  margin: EdgeInsets.only(left: ScreenUtil().setWidth(10)),
                  child: InkWell(
                    onTap: () {
                      index++;
                      if (index >= lenth) {
                        index = 0;
                      }

                      setState(() {});
                    },
                    child: Text(
                      "换一组",
                      style: TextStyles.custom(
                          30, Colors.blueAccent, Font.PingFangRegular),
                    ),
                  ),
                )
              : Container()
        ],
      ),
    );
  }

  Widget getTaskName(String s, String name) {
    return Container(
      margin: EdgeInsets.all(ScreenUtil().setWidth(20)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            child: Text(
              s,
              maxLines: 10,
              overflow: TextOverflow.ellipsis,
              style: getLeftTextStyle(),
            ),
          ),
          Container(
            child: Text(
              name,
              maxLines: 10,
              overflow: TextOverflow.ellipsis,
              style: getLeftTextStyle(),
            ),
          )
        ],
      ),
    );
  }

  getName(String name) {
    List<String> list = name.split("，");
    keyName = list[0];
    setState(() {});
  }

  int getLenth(String name) {
    List<String> list = name.split("，");
    return list.length;
  }

  ///CateFlg3 上面的文字说明
  Widget getCateFlg3Title(TaskStepDataSteparrDetailarrEdit edit) {
    return Container(
      margin: EdgeInsets.only(
          left: ScreenUtil().setWidth(20),
          right: ScreenUtil().setWidth(20),
          top: ScreenUtil().setWidth(30)),
      child: Container(
        child: Text(
          "${edit.wervalue}",
          style: getLeftTextStyle(),
        ),
      ),
    );
  }

  ///CateFlg5 上面的文字说明
  Widget getCateFlgTitle(TaskStepDataSteparrDetailarrEdit edit,
      {bool isShowRight = true}) {
    return Container(
      margin: EdgeInsets.only(
          left: ScreenUtil().setWidth(20), right: ScreenUtil().setWidth(20)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            child: Text(
              "${edit.name}",
              style: getLeftTextStyle(),
            ),
          ),
          isShowRight
              ? Expanded(
                  flex: 1,
                  child: Container(
                    margin: EdgeInsets.only(left: ScreenUtil().setWidth(30)),
                    alignment: Alignment.centerRight,
                    child: Text(
                      "${edit.example}",
                      textAlign: TextAlign.right,
                      maxLines: 10,
                      overflow: TextOverflow.ellipsis,
                      style: getRightTextStyle(),
                    ),
                  ),
                )
              : Container()
        ],
      ),
    );
  }

  getLeftTextStyle() {
    return TextStyles.custom(30, Colours.appC1, Font.PingFangMedium);
  }

  getRightTextStyle() {
    return TextStyles.custom(30, Colours.appC16, Font.PingFangMedium);
  }

  Widget getPics(int i, int j) {
    return Container(
      margin: EdgeInsets.all(ScreenUtil().setWidth(20)),
      child: SelectPicWidget(3, (value) {
        _entity.data.stepArr[i].detailArr.edit[j].value = value.toString();
      }),
    );
  }

  Widget getCateFlg1(
      TaskStepDataSteparrDetailarrEdit edit, TextEditingController controller,
      {String hint = ""}) {
    return Container(
      margin: EdgeInsets.all(ScreenUtil().setWidth(20)),
      child:
          UiUtils.myTextField(context, controller, hintText: hint, maxLines: 2),
    );
  }

  Widget getCateFlg3(
      TaskStepDataSteparrDetailarrEdit edit, TextEditingController controller,
      {String hint = "请输入正确答案"}) {
    return Container(
      margin: EdgeInsets.all(ScreenUtil().setWidth(20)),
      child:
          UiUtils.myTextField(context, controller, hintText: hint, maxLines: 2),
    );
  }

  Widget getCateFlg6(
      TaskStepDataSteparrDetailarrEdit edit, TextEditingController controller) {
    return Container(
      margin: EdgeInsets.all(ScreenUtil().setWidth(20)),
      child: UiUtils.myTextField(context, controller,
          hintText: controller.text, maxLines: 2),
    );
  }

  Widget getText(String s) {
    return Container(
      margin: EdgeInsets.only(left: ScreenUtil().setWidth(20)),
      child: Text(
        s,
        maxLines: 10,
        overflow: TextOverflow.ellipsis,
        style:
            TextStyles.custom(28, Colours.appC1, Font.PingFangRegular),
      ),
    );
  }

  Widget getCateFlg4(List example) {
    List<Widget> widgets = [];
    for (int i = 0; i < example.length; i++) {
      String str = example[i]['url'];
      widgets.add(getSavePicWidget(str));
    }
    return Container(
      margin: EdgeInsets.only(
          bottom: ScreenUtil().setWidth(30), right: ScreenUtil().setWidth(20)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: widgets,
      ),
    );
  }

  Widget getCateFlg5(String value) {
    List<Widget> widgets = [];
    List<String> listStr = value.split(",");
    for (int i = 0; i < listStr.length; i++) {
      String str = listStr[i];
      String url = str.replaceAll("[", "").replaceAll("]", "").trim();
      widgets.add(Container(
        margin: EdgeInsets.all(ScreenUtil().setWidth(20)),
        child: UiUtils.cachedNetworkImage(180, 180, url),
      ));
    }
    return Container(
      margin: EdgeInsets.only(bottom: ScreenUtil().setWidth(30)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: widgets,
      ),
    );
  }

  Widget getSavePicWidget(String url) {
    return Container(
      margin: EdgeInsets.only(left: ScreenUtil().setWidth(30)),
      child: SavePicWidget(url),
    );
  }

  getMargin() {
    return EdgeInsets.fromLTRB(
        ScreenUtil().setWidth(20),
        ScreenUtil().setWidth(10),
        ScreenUtil().setWidth(20),
        ScreenUtil().setWidth(20));
  }

  ///核对
  Widget getButton(String text, int i, int j) {
    return GestureDetector(
      onTap: () {
        if (text.isEmpty) {
          ToastUtil.showShortErrToast("请输入要核对的内容");
          return;
        }
        UiUtils.showMyDialog(context, text: "正在核对...");
        this.check(text, i, j);
      },
      child: Container(
        margin: EdgeInsets.only(
            left: ScreenUtil().setWidth(180),
            right: ScreenUtil().setWidth(180)),
        padding: EdgeInsets.only(
            top: ScreenUtil().setWidth(6), bottom: ScreenUtil().setWidth(6)),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: _entity.data.stepArr[i].detailArr.edit[j].check == 1
                ? Colors.green
                : Colours.appC16,
            borderRadius: BorderRadius.circular(16)),
        child: Text(
          _entity.data.stepArr[i].detailArr.edit[j].check == 1
              ? "核对成功"
              : "粘贴并核对",
          textAlign: TextAlign.center,
          style: TextStyles.custom(
              30, Colors.white, Font.PingFangRegular),
        ),
      ),
    );
  }

  //展示的第二种情况 显示图片
  Widget getBrowseItem2(TaskStepDataSteparrDetailarrBrowse browse) {
    return Container(
      margin: EdgeInsets.all(ScreenUtil().setWidth(20)),
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child:
                Container(child: Text(browse.name, style: getLeftTextStyle())),
          ),
          Container(
            child:
                PhotoHeroUtil.photoHeroNet(context, browse.value, width: 200.0),
          )
        ],
      ),
    );
  }

  Widget getBottom(int i) {
    if (currentStep != i) {
      ///不可点击状态
      return Container(
        margin: getMargin(),
        child: UiUtils.bottomBotton("提交", () {}, clickAble: false),
      );
    }

    if (currentState != 0) {
      ///不可点击状态
      return Container(
        margin: getMargin(),
        child: UiUtils.bottomBotton("等待商家审核", () {}, clickAble: false),
      );
    }

    //显示倒计时
    if (bottomTime > 0) {
      return Container(
        alignment: Alignment.center,
        margin: getMargin(),
        width: ScreenUtil().setWidth(750),
        height: ScreenUtil().setWidth(88),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(30),
          color: Colours.appC4,
        ),
        child: Consumer<TaskTimerBottomModel>(
          builder: (context, TaskTimerBottomModel model, _) {
            if (null == model.second) {
              model.upSecond(bottomTime);
            }
            if (bottomTime != model.second) {
              model.upSecond(bottomTime);
            }
            return TimerWidget(
              model.second,
              onRun: (value) {
                if (mounted) {
                  bottomTime = value;
                  model.upSecond(value);
                }
              },
              onFinsh: () {
                setState(() {});
              },
              end: " 后提交",
              hour: ":",
              min: ":",
              second: "",
              color: 0xFFFFFFFF,
              fontSize: 32.0,
            );
          },
        ),
      );
    }

    ///1.可以点击
    return Container(
      margin: getMargin(),
      child: UiUtils.bottomBotton("提交", () {
        ///1.校验
        bool isOk = checkData(i);

        if (isOk) {
          ///获取数据
          String upJson = getUpJson(i);
          UiUtils.showMyDialog(context, text: "正在提交");

          ///3.上传数据
          upData(i + 1, upJson);
        }
      }),
    );
  }

  bool checkData(int i) {
    ///展示要 edit 的信息
    for (int j = 0; j < _entity.data.stepArr[i].detailArr.edit.length; j++) {
      TaskStepDataSteparrDetailarrEdit edit =
          _entity.data.stepArr[i].detailArr.edit[j];

      /// 1.输入文本
      if (edit.cateFlg == 1) {
        if (edit.value == "") {
          ToastUtil.showShortErrToast("请填写反馈内容");
          return false;
        }
        continue;
      }

      /// 3.输入答案
      if (edit.cateFlg == 3) {
        if (edit.value == "") {
          ToastUtil.showShortErrToast("请填写反馈内容");
          return false;
        }
        continue;
      }

      /// 4.显示图片组
      if (edit.cateFlg == 4) {
        continue;
      }

      /// 5.上传图片组
      if (edit.cateFlg == 5) {
        print("上传图片组");
        print("${edit.value}");
        //
        if (edit.value == "" || edit.value == "[]") {
          ToastUtil.showShortErrToast("请上传图片");
          return false;
        }
        continue;
      }

      /// 6.输入 粘贴并核对
      if (edit.cateFlg == 6) {
        ///校验----
        if (edit.check != 1) {
          ToastUtil.showShortErrToast("请先进行产品核对！");
          return false;
        }
        continue;
      }
    }

    return true;
  }

  getUpJson(int i) {
    StringBuffer sb = StringBuffer();
    sb.write("[");

    ///展示要 edit 的信息
    for (int j = 0; j < _entity.data.stepArr[i].detailArr.edit.length; j++) {
      TaskStepDataSteparrDetailarrEdit edit =
          _entity.data.stepArr[i].detailArr.edit[j];

      /// 1.输入文本
      if (edit.cateFlg == 1) {
        sb.write("{\"id\":\"${edit.id}\",");
        sb.write("\"name\":\"${edit.name}\",");
        sb.write("\"value\":\"${edit.value}\",");
        sb.write("\"usrtype\":\"${edit.usrtype}\",");
        sb.write("\"example\":\"${edit.example}\",");
        sb.write("\"cateFlg\":${edit.cateFlg}}");
        if (j != _entity.data.stepArr[i].detailArr.edit.length - 1) {
          sb.write(",");
        }
      }

      /// 3.输入答案（需要校验）
      if (edit.cateFlg == 3) {
        sb.write("{\"id\":\"${edit.id}\",");
        sb.write("\"name\":\"${edit.name}\",");
        sb.write("\"value\":\"${edit.value}\",");
        sb.write("\"usrtype\":\"${edit.usrtype}\",");
        sb.write("\"example\":\"${edit.example}\",");
        sb.write("\"cateFlg\":${edit.cateFlg}}");
        if (j != _entity.data.stepArr[i].detailArr.edit.length - 1) {
          sb.write(",");
        }
      }

      /// 4.显示图片组
      if (edit.cateFlg == 4) {}

      /// 5.上传图片组
      if (edit.cateFlg == 5) {
        sb.write("{\"id\":\"${edit.id}\",");
        sb.write("\"name\":\"${edit.name}\",");

        ///将字符串 处理为数组上传
        List<String> picsStr = edit.value.split(",");
        StringBuffer sbValue = StringBuffer();
        sbValue.write("[");

        for (int i = 0; i < picsStr.length; i++) {
          sbValue.write("\"");
          String s = picsStr[i].replaceAll("[", "").replaceAll("]", "");
          sbValue.write(s);
          sbValue.write("\"");
          if (i != picsStr.length - 1) {
            sbValue.write(",");
          }
        }

        sbValue.write("]");

        sb.write("\"value\":$sbValue,");
        sb.write("\"example\":\"${edit.example}\",");
        sb.write("\"cateFlg\":${edit.cateFlg}}");

        if (j != _entity.data.stepArr[i].detailArr.edit.length - 1) {
          sb.write(",");
        }
      }

      /// 6.输入 粘贴并核对
      if (edit.cateFlg == 6) {
        sb.write("{\"id\":\"${edit.id}\",");
        sb.write("\"name\":\"${edit.name}\",");
        sb.write("\"value\":\"${edit.value}\",");
        sb.write("\"usrtype\":\"${edit.usrtype}\",");
        sb.write("\"example\":\"${edit.example}\",");
        sb.write("\"cateFlg\":${edit.cateFlg}}");
        if (j != _entity.data.stepArr[i].detailArr.edit.length - 1) {
          sb.write(",");
        }
      }
    }
    sb.write("]");
    return sb.toString();
  }

  //提交数据
  void upData(int i, String upJson) {
    FormData formData =
        FormData.from({"id": widget.id, "step": i, "pictureArr": upJson});

    DioManager.getInstance().post(Api.TASK_DOTASK, formData, (json) {
      DotaskEntity dotaskEntity = null;
      try {
        dotaskEntity = DotaskEntity.fromJson(json);
      } catch (e) {
        ToastUtil.showShortErrToast(Api.ERR_DATA);
        NavigatorUtils.goBack(context);
        return;
      }

      if (null == dotaskEntity) {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        NavigatorUtils.goBack(context);
        return;
      }
      if (dotaskEntity.code != 200) {
        ToastUtil.showShortErrToast(dotaskEntity.message);
        NavigatorUtils.goBack(context);
        return;
      }

      ///当前步骤的状态
      currentState = dotaskEntity.data.state;

      ///1.跳转到下一步
      if (i <= _entity.data.stepArr.length - 1) {
        _swiperController.next();
        currentStep++;
      } else {
        ///2.全部任务结束
        NavigatorUtils.goBack(context);
        NavigatorUtils.goBack(context);
        return;
      }

      ///底部倒计时的时间
      bottomTime = dotaskEntity.data.endtime - dotaskEntity.data.current;
      setState(() {});
      NavigatorUtils.goBack(context);
    }, (err) {
      ToastUtil.showShortErrToast(Api.ERR_TIME_OUT);
      NavigatorUtils.goBack(context);
    });
  }

  void check(String text, int i, int j) {
    FormData params = FormData.from({"id": widget.id, "check": text});
    DioManager.getInstance().post(Api.TASK_CHECK, params, (json) {
      BaseEntity entity = BaseEntity.fromJson(json);
      if (null == entity) {
        _entity.data.stepArr[i].detailArr.edit[j].check = 0;
        NavigatorUtils.goBack(context);
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        return;
      }
      if (entity.code != 200) {
        _entity.data.stepArr[i].detailArr.edit[j].check = 0;
        NavigatorUtils.goBack(context);
        ToastUtil.showShortErrToast(entity.message);
        return;
      }

      _entity.data.stepArr[i].detailArr.edit[j].check = 1;

      setState(() {});
      NavigatorUtils.goBack(context);
    }, (err) {
      _entity.data.stepArr[i].detailArr.edit[j].check = 0;
      NavigatorUtils.goBack(context);
      ToastUtil.showShortErrToast(Api.ERR_NOTHING);
      return;
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  getRowTimer() {
    return Container(
      margin: EdgeInsets.only(top: ScreenUtil().setWidth(10)),
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(left: ScreenUtil().setWidth(15)),
            child: Text(
              "任务将在",
              style: TextStyles.custom(
                  28, Colours.appC2, Font.PingFangMedium),
            ),
          ),
          Container(
            child: Consumer<TaskTimerModel>(
              builder: (context, TaskTimerModel model, _) {
                if (null == model.second) {
                  model.upSecond(topTime);
                }
                if (topTime != model.second) {
                  model.upSecond(topTime);
                }

                return TimerWidget(
                  model.second,
                  onFinsh: () {
                    setState(() {});
                  },
                  onRun: (value) {
                    topTime = value;
                    model.upSecond(value);
                  },
                  end: "",
                  hour: ":",
                  min: ":",
                  second: "",
                  color: 0xFFFF5000,
                  fontSize: 32.0,
                );
              },
            ),
          ),
          Container(
            child: Text(
              "后自动截止",
              style: TextStyles.custom(
                  28, Colours.appC2, Font.PingFangMedium),
            ),
          ),
        ],
      ),
    );
  }

/*  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
        break;
      case AppLifecycleState.resumed: // 应用程序可见，前台
        this.getData();
        break;
      case AppLifecycleState.paused: // 应用程序不可见，后台
        break;
      case AppLifecycleState.suspending: // 申请将暂时暂停
        break;
    }
  }*/
}
